/*
 * @Author: lijunqing
 * @Date: 2024-04-10 10:21:43
 * @LastEditors: lijunqing
 * @LastEditTime: 2024-04-10 11:34:17
 * @Description:
 */

const fs = require("fs");

// 同步文件导入

const txt = fs.readFileSync("./main/footer/footer.txt", { encoding: "utf-8" });

// 异步

fs.readFile("./main/footer/footer.txt", { encoding: "utf-8" }, (err, data) => {
  if (err) return;
});

// promise

fs.promises
  .readFile("./main/footer/footer.txt", { encoding: "utf-8" })
  .then((res) => {})
  .catch(() => {});

// 文件描述符

// 1、打开文件
fs.open("./main/footer/footer.txt", (err, fd) => {
  if (err) return;

  fs.fstat(fd, (err, stat) => {
    console.log(
      new Date().getFullYear(stat.ctimeMs) +
        "年" +
        (new Date().getMonth(stat.ctimeMs) + 1) +
        "月" +
        new Date().getDate(stat.ctimeMs) +
        "日" +
        new Date().getHours(stat.ctimeMs) +
        ":" +
        new Date().getMinutes(stat.ctimeMs)
    );
    fs.close(fd);
  });
});

// 创建文件夹

// fs.mkdir("./creatDir", (err) => {});

// 读取文件夹详细内容
fs.readdir("./main", { withFileTypes: true }, (err, files) => {
  console.log(files); // Array 形式
  files.forEach((item) => {
    if (item.isDirectory()) {
      fs.readdir(`./main/${item.name}`, { withFileTypes: true }, (err, files) => {
        //   console.log(item.name, files);
      });
    }
  });
});

// 递归读取

function readDirectory(path) {
  fs.readdir(path, { withFileTypes: true }, (err, files) => {
    files.forEach((item) => {
      if (item.isDirectory()) {
        readDirectory(`${path}/${item.name}`);
      } else {
        console.log("获取文件", item.name);
      }
    });
  });
}

readDirectory("./main");

// 重命名文件夹

fs.rename("./creatDir", "./xxx", (err) => {});
